/*
 *@author: YangJie
 *@date: 2021-04-19 16:23:09
 *@version:
 *@description: 参数设置->系统管理->设备类型
 */
import React from 'react';
import { Button, Form, Tabs, Table, Modal, Input, Checkbox, message } from 'antd';
import '@/assets/css/settings';
import { get, post } from '../../../axios/http';
import { euqApplicationName } from '../../../config';

const { TabPane } = Tabs;

/*
 * useAutoCode - 项目内非重要值，可忽略
 */

const DocumentType2Form = React.forwardRef(function DocumentType2Form({ form, form: { getFieldDecorator }}, ref) {
	React.useImperativeHandle(ref, () => ({ form }));

	return (
		<Form>
			<Form.Item label="设备类型名称">
			{getFieldDecorator('name', {
				rules: [
					{
						required: true,
						message: '必须要输入一个名称',
					},
				],
			})(<Input />)}
			</Form.Item>
			<Form.Item label="设备类型编码">
			{getFieldDecorator('code')(<Input />)}
			</Form.Item>
			<Form.Item>
			{getFieldDecorator('sign', {
				valuePropName: 'checked',
				initialValue: false,
			})(<Checkbox>重点设备</Checkbox>)}
			</Form.Item>
			<Form.Item>
			{getFieldDecorator('useAutoCode', {
				valuePropName: 'checked',
				initialValue: true,
			})(<Checkbox>使用自动编码</Checkbox>)}
			</Form.Item>
			<Form.Item>
			{getFieldDecorator('pid', {
				initialValue: 0,
			})(<Input type="hidden" />)}
			</Form.Item>
		</Form>
	);
});

function DocumentType2() {
	const [data, setData] = React.useState([]);
	const [selected, setSelected] = React.useState([]);
	const [selectedRow, setSelectedRow] = React.useState([]);
	const [action, setAction] = React.useState();
	const [showModal, setShowModal] = React.useState(false);
	const [modalData, setModalData] = React.useState({});
	const [modalTitle,setModalTitle] = React.useState('')
	const [showModal2, setShowModal2] = React.useState(false);
	const [showLoading2, setShowLoading2] = React.useState(true);
	const [modal2Data, setModal2Data] = React.useState([]);
	const [modal2DataAdd, setModal2DataAdd] = React.useState({});
	const [row, setRow] = React.useState({});
	const formRef = React.useRef();
	const regionAdd = React.useCallback((e)=>{
		console.log(e)
		setRow(e)
		return get(euqApplicationName + '/parameter_setting_equipmentType/findEquTypeRegionPageList/'+e.id).then((res) => {
			setModal2Data(res.data);
			setShowModal2(true)
			setShowLoading2(false)
		});
	})
	const changeInput = React.useCallback((e)=>{
		setModal2DataAdd({'name':e.target.value})
	})
	const addModal = React.useCallback(()=>{
		console.log(modal2DataAdd)
		if(modal2DataAdd.name){
			setShowLoading2(true)
			modal2DataAdd.createrId = localStorage.getItem('userId')
			modal2DataAdd.equTypeId = row.id
			return post(euqApplicationName + '/parameter_setting_equipmentType/addEquTypeRegion',{data:modal2DataAdd}).then((res) => {
				console.log(res)
				regionAdd(row)
				setShowLoading2(false)
			});
		}else{
			return setShowLoading2(false)
		}
		
	})
	const regionDelete = React.useCallback((e)=>{
		setShowLoading2(true)
		return get(euqApplicationName + '/parameter_setting_equipmentType/deleteEquTypeRegion/'+e.id).then((res) => {
			regionAdd(row)
			setShowLoading2(false)
		});
	})
	const fetchData = React.useCallback(() => {
		return get(euqApplicationName + '/parameter_setting_equipmentType/findEquTypePageList').then((res) => {
			setData(res.data);
		});
	}, []);
	const handleModalOk2 = React.useCallback(() => {
		return get(euqApplicationName + '/parameter_setting_equipmentType/findEquTypePageList').then((res) => {
			setData(res.data);
		});
	}, []);
	const handleExtraClick = React.useCallback((e) => {
		const type = e.currentTarget.getAttribute('data-action');
		setAction(type);
		switch (type) {
			case 'addSame': {
				if (selected.length > 1) {
					Modal.info({
						title: '你最多只能选择一个条目',
					});
					return;
				}
				setModalData({});
				setModalTitle('添加同级');
				setShowModal(true);
				break;
			}

			case 'addChildren': {
				if (selected.length !== 1) {
					Modal.info({
						title: '你必须/只能选择一个条目',
					});
					return;
				}
				setModalData({});
				setModalTitle('添加下级');
				setShowModal(true);
				break;
			}

			case 'modify': {
				if (selected.length !== 1) {
					Modal.info({
						title: '你必须/只能选择一个条目',
					});
					return;
				}
				setModalData(selectedRow[0]);
				setModalTitle('修改');
				setShowModal(true);
				break;
			}

			case 'delete': {
				if (selected.length === 0) {
					Modal.info({
						title: '你必须选择一个条目',
					});
					return;
				}
				Modal.confirm({
					title: '你确定要删除这些设备吗？',
					onOk() {
						// console.log('delete:', selected)
						get(euqApplicationName + '/parameter_setting_equipmentType/deleteEquTypeList', { params: { ids: selected.join(','), _: Date.now() } }, true).then((res) => {
							message.info('删除成功');
							setModalData({});
							setSelected([]);
						}).then(() => {
							return fetchData();
						}).catch(() => {
							message.error('发生了网络错误');
							setShowModal(false);
						});
					},
				});
				break;
			}
		}
	}, [selected, selectedRow]);
	const handleModalOk = React.useCallback((e) => {
		formRef.current.form.validateFields((err, values) => {
			if (err) {
				return;
			}
			switch (action) {
				case 'addSame':
				case 'addChildren': {
					let pid = 0;
					if (action === 'addChildren') {
						pid = selected[0];
					}
					if (action === 'addSame' && selected.length > 0) {
						pid = selectedRow[0].pid;
					}
					const reqData = {
						createId: 0,
						id: 0,
						...values,
						pid,
					};
					console.log('add:', reqData)
					reqData.sign = reqData.sign ? 1 : 0
					post(euqApplicationName + '/parameter_setting_equipmentType/addEquType', { data: reqData }, true).then((res) => {
						message.info('添加成功');
						setShowModal(false);
						setSelected([]);
					}).then(() => {
						return fetchData();
					}).catch(() => {
						message.error('发生了网络错误');
						setShowModal(false);
					});
					break;
				}

				case 'modify': {
					const reqData = {
						createId: 0,
						id: selected[0],
						...values,
					};
					// console.log('modify:', reqData)
					post(euqApplicationName + '/parameter_setting_equipmentType/editEquType', { data: reqData }, true).then((res) => {
						message.info('添加成功');
						setShowModal(false);
						setSelected([]);
					}).then(() => {
						return fetchData();
					}).catch(() => {
						message.error('发生了网络错误');
						setShowModal(false);
					});
					break;
				}
			}
			
		});
	}, [action, selected]);
	const handleModalCancel = React.useCallback((e) => {
		setShowModal(false);
	}, []);
	
	const handleModalCancel2 = React.useCallback((e) => {
		setShowModal2(false);
		fetchData()
	}, []);

	const columns = [
		{
			title: '设备类型',
			dataIndex: 'name',
			key: 'name',
		},
		{
			title: '设备类型编码',
			dataIndex: 'code',
			key: 'code',
		},
		{
			title: '重点设备',
			dataIndex: 'sign',
			key: 'sign',
			render: (text, row, index) => {
				return text ? '是' : '否';
			},
		},
		{
			title: '部位',
			dataIndex: 'regionName',
			key: 'regionName',
			render: (text, row, index) => {
				return <a onClick={()=>{regionAdd(row)}}>{text ? text : '添加'}</a>;
			},
		},
	];
	const columnss = [
		{
			title: '删除',
			render: (text, row, index) => {
				return <a onClick={()=>{regionDelete(row)}}>删除</a>;
			},

		},
		{
			title: '部位名称',
			dataIndex:'name'

		},
	];
	const rowSelection = {
		selectedRowKeys: selected,
		onChange: (selectedRowKeys, selectedRows) => {
			// console.log(selectedRowKeys, selectedRows)
			setSelected(selectedRowKeys);
			setSelectedRow(selectedRows);
		},
	};

	const extraContent = (
		<div className="buttonList">
			<Button icon="plus" type="primary" data-action="addSame" onClick={handleExtraClick}>添加同级</Button>
			<Button icon="minus" type="primary" data-action="addChildren" onClick={handleExtraClick}>添加下级</Button>
			<Button icon="edit" type="primary" data-action="modify" onClick={handleExtraClick}>修改</Button>
			<Button icon="delete" type="primary" data-action="delete" onClick={handleExtraClick}>删除</Button>
		</div>
	);
	const DocumentType2FormWrap = React.useMemo(() => {
		return Form.create({
			mapPropsToFields(props) {
				return (props.data && props.data.name) ? {
					name: Form.createFormField({ value: props.data.name }),
					code: Form.createFormField({ value: props.data.code }),
					sign: Form.createFormField({ value: props.data.sign || false }),
					useAutoCode: Form.createFormField({ value: props.data.useAutoCode || true }),
					pid: Form.createFormField({ value: props.data.pid }),
				} : {};
			}
		})(DocumentType2Form);
	}, [modalData]);

	React.useEffect(() => {
		fetchData();
	}, []);

	return (
		<>
			<div className="shadow-radius">
				<Tabs tabBarExtraContent={extraContent}>
					<TabPane tab="设备类型" key="1">
						{ data && data.length > 0 ?
							<Table dataSource={data} rowKey="id" columns={columns} rowSelection={rowSelection} pagination={false}  defaultExpandAllRows={true}/>
							: '暂无数据'
						}
					</TabPane>
				</Tabs>
			</div>
			<Modal title={modalTitle} visible={showModal} onOk={handleModalOk} onCancel={handleModalCancel}>
				<DocumentType2FormWrap wrappedComponentRef={formRef} data={modalData} />
			</Modal>
			
			<Modal title="添加部位" visible={showModal2} onOk={handleModalCancel2} onCancel={handleModalCancel2}>
				<div style={{display:'flex',justifyContent:'space-around'}}>

					<Input  style={{width:'80%'}} onChange={changeInput}/><a style={{fontSize:18}} onClick={addModal}>添加</a>
				</div>
				<Table dataSource={modal2Data} rowKey="id" columns={columnss} pagination={false} loading={showLoading2}/>
			</Modal>
		</>
	);
}

export default DocumentType2;
